package com.yfqy.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.yfqy.admin.conf.Idgenerator.SnowflakeIdGenerator;
import com.yfqy.admin.constant.MyConstants;
import com.yfqy.admin.domain.dto.QueryById;
import com.yfqy.admin.domain.dto.label.AddLabel;
import com.yfqy.admin.domain.dto.label.LabelDTO;
import com.yfqy.admin.domain.dto.label.ModifiedLabel;
import com.yfqy.admin.domain.entity.Label;
import com.yfqy.admin.domain.mapper.LabelMapper;
import com.yfqy.admin.transform.UserNameTranslator;
import com.yfqy.admin.security.login.LoginUserInfo;
import com.yfqy.admin.service.LabelService;
import com.yfqy.admin.util.AuthUserContext;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

@Service
public class LabelServiceImpl implements LabelService {

    private final LabelMapper labelMapper;
    private final SnowflakeIdGenerator snowflakeIdGenerator;
    private final UserNameTranslator userNameTranslator;

    public LabelServiceImpl(LabelMapper labelMapper, SnowflakeIdGenerator snowflakeIdGenerator,
                            UserNameTranslator userNameTranslator) {
        this.labelMapper = labelMapper;
        this.snowflakeIdGenerator = snowflakeIdGenerator;
        this.userNameTranslator = userNameTranslator;
    }

    // 新增标签
    @Override
    public int addLabel(AddLabel addLabel) {
        // 检查标签名称是否已存在
        if (labelMapper.countByLabelName(addLabel.getLabelName(), null) > 0) {
            throw new IllegalArgumentException("标签名称已存在");
        }
        LoginUserInfo loginUserInfo = AuthUserContext.getLocalAuthUser();
        Long createdBy = Objects.nonNull(loginUserInfo) ? loginUserInfo.getId() : MyConstants._L1;
        Label label = new Label();
        label.setId(snowflakeIdGenerator.nextId());
        label.setLabelName(addLabel.getLabelName());
        label.setCreatedBy(createdBy);
        label.setModifiedBy(createdBy);
        return labelMapper.insertSelective(label);
    }

    //删除标签
    @Override
    public int deleteLabel(QueryById queryById) {
        return labelMapper.deleteByPrimaryKey(queryById.getId());
    }

    // 更新标签
    @Override
    public int updateLabel(ModifiedLabel label) {
        if (!StringUtils.hasText(label.getLabelName())) {
            throw new IllegalArgumentException("标签名称不能为空");
        }
        // 检查标签名称是否已存在（排除自己）
        if (labelMapper.countByLabelName(label.getLabelName(), label.getId()) > 0) {
            throw new IllegalArgumentException("标签名称已存在");
        }
        LoginUserInfo loginUserInfo = AuthUserContext.getLocalAuthUser();
        Long modifiedBy = Objects.nonNull(loginUserInfo) ? loginUserInfo.getId() : MyConstants._L1;
        Label modified = new Label();
        modified.setId(label.getId());
        modified.setModifiedBy(modifiedBy);
        if (label.getStatus() != null) modified.setStatus(label.getStatus());
        return labelMapper.updateByPrimaryKeySelective(modified);
    }


    // 查询标签列表（可根据名称和状态筛选）
    @Override
    public List<LabelDTO> getLabelList(String labelName, Integer status) {
        List<LabelDTO> labelDTOS = labelMapper.selectAll(labelName, status);
        if (CollUtil.isNotEmpty(labelDTOS)) {
            /*List<Long> sysUserIds = new ArrayList<>();
            labelDTOS.forEach(label -> {
                sysUserIds.add(label.getCreatedBy());
                sysUserIds.add(label.getModifiedBy());
            });
            List<SysUser> sysUsers = sysUserMapper.selectByIds(sysUserIds);
            if (CollUtil.isNotEmpty(sysUsers)) {
                // 所有记录中的后台管理员id
                Map<Long, SysUser> sysUserMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getId, Function.identity()));
                labelDTOS.forEach(label -> {
                    label.setCreatedByName(Optional.ofNullable(sysUserMap.get(label.getCreatedBy()))
                            .map(user -> String.format("%s(%s)", user.getNickname(), user.getUsername())).orElse("-"));
                    label.setModifiedByName(Optional.ofNullable(sysUserMap.get(label.getModifiedBy()))
                            .map(user -> String.format("%s(%s)", user.getNickname(), user.getUsername())).orElse("-"));
                });
            }*/
            userNameTranslator.translationUser(labelDTOS);
        }
        return labelDTOS;
    }

}
